package com.qd.panda.card;

import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.exception.ApiException;
import com.qd.common.sys.enums.RemoteEnum;
import com.qd.common.sys.util.SecurityUtils;
import com.qd.panda.service.card.UserCardShareService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.Map;

/**
 * 优惠券/APP_优惠券分享
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/app/userShareCard/")
@Slf4j
public class AppUserShareCardController {
    private final UserCardShareService userCardShareService;

    /**
     * 分享卡劵
     *
     * @param map 劵ID
     */
    @PostMapping(value = "/shareCardId")
    public ApiResultWrapper<Object> shareCardId(@Validated @RequestBody Map<String, String> map) {
        String cardId = map.get("cardId");
        if (!StringUtils.hasLength(cardId)) {
            return ApiResult.error("劵ID不能为空");
        }
        String userId = SecurityUtils.getLoginUser().getUserId();
        String remote = SecurityUtils.getLoginUser().getRemote();
        if (!remote.equals(RemoteEnum.MINI_PROGRAM.getCode())) {
            throw new ApiException("当前用户没有权限访问");
        }
        String mobile = SecurityUtils.getLoginUser().getUser().getAppUserExtend().getMobile();
        return ApiResult.success(userCardShareService.shareCardId(cardId, userId, mobile));
    }

    /**
     * 领取卡劵
     *
     * @param map 劵ID
     */
    @PostMapping(value = "/receiveCardId")
    public ApiResultWrapper<Object> receiveCardId(@Validated @RequestBody Map<String, String> map) {
        String shareId = map.get("shareId");
        if (!StringUtils.hasLength(shareId)) {
            return ApiResult.error("分享ID不能为空");
        }
        String userId = SecurityUtils.getLoginUser().getUserId();
        String remote = SecurityUtils.getLoginUser().getRemote();
        if (!remote.equals(RemoteEnum.MINI_PROGRAM.getCode())) {
            throw new ApiException("当前用户没有权限访问");
        }
        String mobile = SecurityUtils.getLoginUser().getUser().getAppUserExtend().getMobile();
        userCardShareService.receiveCardId(shareId, userId, mobile);
        return ApiResult.success();
    }

    /**
     * 卡劵详情及领取情况
     *
     * @param shareId 分享ID
     */
    @GetMapping(value = "/cardInfoByShareId")
    public ApiResultWrapper<Object> cardInfoByShareId(@Validated @NotBlank(message = "分享ID不能为空") String shareId) {
        return ApiResult.success(userCardShareService.cardInfoByShareId(shareId));
    }
}